﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

namespace Nano.Core.Config
{
    public class ExtensionElement : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get { return (string)base["name"]; }
            set { base["name"] = value; }
        }

        [ConfigurationProperty("enabled", IsRequired = true)]
        public bool Enabled
        {
            get { return (bool)base["enabled"]; }
            set { base["enabled"] = value; }
        }
    }

    [ConfigurationCollection(typeof(ExtensionElement), AddItemName = "extension", CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class ExtensionElementCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ExtensionElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ExtensionElement)element).Name;
        }

        public void Add(ExtensionElement element)
        {
            BaseAdd(element);
        }

        public void Clear()
        {
            BaseClear();
        }

        public int IndexOf(ExtensionElement element)
        {
            return BaseIndexOf(element);
        }

        public void Remove(ExtensionElement element)
        {
            if (BaseIndexOf(element) >= 0)
            {
                BaseRemove(element.Name);
            }
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        public ExtensionElement this[int index]
        {
            get { return (ExtensionElement)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }
    }

    public class ExtensionsSection : ConfigurationSection
    {
        private static readonly ConfigurationProperty _propExtensions = new ConfigurationProperty(
                null,
                typeof(ExtensionElementCollection),
                null,
                ConfigurationPropertyOptions.IsDefaultCollection
        );

        private static ConfigurationPropertyCollection _properties = new ConfigurationPropertyCollection();

        static ExtensionsSection()
        {
            _properties.Add(_propExtensions);
        }

        [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
        public ExtensionElementCollection Extensions
        {
            get { return (ExtensionElementCollection)base[_propExtensions]; }
        }
    }

}